package org.jsbd.boss.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeoutException;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jsbd.boss.common.GetUpdateResult;
import org.jsbd.boss.domian.DoRegsInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import edu.hziee.cap.common.util.IpUtils;
import edu.hziee.cap.common.xip.AbstractXipRequest;

public class HttpUtil {
    private static Logger logger = LoggerFactory.getLogger(HttpUtil.class);
    public static Random r = new Random();
    public static String getIpAddr(AbstractXipRequest req) {
        return IpUtils.getIpPortPair(req);
    }

    // 2.1.2
    public static String getInfo(String srcUrl, int timeoutMils, String imei, String imsi, String version, String sdkSessionId, String random)
            throws IOException {
        String signerContent = "+Signature-OF-Secret+POST+Encrypt-IMSI=" + imsi + "&Random-Code=" + random;
        String signer = RegsUtils.encryptSHA1(signerContent);
        URL url = new URL(srcUrl + "Random-Code=" + random + "&Encrypt-IMSI=" + imsi);
        HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
        httpconn.setRequestProperty("Accept", "application/xml");
        httpconn.setRequestProperty("Accept-Encoding", "gzip");
        httpconn.setRequestProperty("apiVersion", "2.0");
        httpconn.setRequestProperty("imei", imei);
        httpconn.setRequestProperty("imsi", imsi);
        httpconn.setRequestProperty("OS_TYPE", "1");
        httpconn.setRequestProperty("platform", "Android");
        httpconn.setRequestProperty("Response-Type", "xml");
        httpconn.setRequestProperty("sdkSessionId", sdkSessionId);
        httpconn.setRequestProperty("SDKVersion", version);
        httpconn.setRequestProperty("signer", signer);
        httpconn.setRequestProperty("X-OF-KEY", "Signature-OF-RSAUtils");
        httpconn.setRequestProperty("X-OF-Signature", signer);
        httpconn.setReadTimeout(timeoutMils);

        InputStreamReader inputReader = new InputStreamReader(httpconn.getInputStream());
        BufferedReader bufReader = new BufferedReader(inputReader);

        String tmpLine = "";
        StringBuffer contentBuffer = new StringBuffer();

        while ((tmpLine = bufReader.readLine()) != null) {
            contentBuffer.append(tmpLine);
        }

        bufReader.close();
        httpconn.disconnect();
        return contentBuffer.toString();
    }
    
    

    public static String getInfo(String srcUrl, int timeoutMils) throws IOException {
        URL url = new URL(srcUrl);
        HttpURLConnection httpconn = (HttpURLConnection) url.openConnection();
        httpconn.setReadTimeout(timeoutMils);

        InputStreamReader inputReader = new InputStreamReader(httpconn.getInputStream());
        BufferedReader bufReader = new BufferedReader(inputReader);

        String tmpLine = "";
        StringBuffer contentBuffer = new StringBuffer();

        while ((tmpLine = bufReader.readLine()) != null) {
            contentBuffer.append(tmpLine);
        }

        bufReader.close();
        httpconn.disconnect();
        return contentBuffer.toString();
    }

    
    public static void login(String cid, String chid, String cpid, String imei, String imsi, String sdkSessionId, String userToken,String model, String sdkVersion, DoRegsInfo info) throws TimeoutException {
        String signerContent = "+Signature-OF-Secret+POST+channelId=" + chid + "&contentId=" +cid+ "&gameId=&loginType=2&needTel=1&userToken=" + userToken;
        String signer = RegsUtils.encryptSHA1(signerContent);
        try {
            HttpPost httpPost = new HttpPost("http://drm.cmgame.com/egsb/access/login");
            ArrayList<NameValuePair> form = new ArrayList();
            form.add(new BasicNameValuePair("loginType", "2"));
            form.add(new BasicNameValuePair("gameId", ""));
            form.add(new BasicNameValuePair("contentId", cid));
            form.add(new BasicNameValuePair("channelId", chid));
            form.add(new BasicNameValuePair("userToken", userToken));
            form.add(new BasicNameValuePair("needTel", "1"));
            form.add(new BasicNameValuePair("tokenType", "0"));
            
            httpPost.addHeader("Accept", "application/xml");
            httpPost.addHeader("Accept-Encoding", "gzip");

            httpPost.addHeader("apiVersion", "2.0");

            httpPost.addHeader("imei", imei);
            httpPost.addHeader("imsi", imsi);

            httpPost.addHeader("OS_TYPE", "1");
            httpPost.addHeader("platform", "Android");
            httpPost.addHeader("Response-Type", "xml");
            httpPost.addHeader("sdkSessionId", sdkSessionId);
            httpPost.addHeader("SDKVersion", sdkVersion);
            httpPost.addHeader("signer", signer);
            httpPost.addHeader("X-OF-KEY", "Signature-OF-RSAUtils");
            httpPost.addHeader("X-OF-Signature", signer);
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(form, "UTF-8");
            urlEncodedFormEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            httpPost.setEntity(urlEncodedFormEntity);
            HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
                Document doc = DocumentHelper.parseText(result);
                Element rootElement = doc.getRootElement();// 获取根节点
                Element submit = doc.getRootElement().element("userInfo");
                if(submit==null){
                  logger.warn(result);
                  info.setResultCode(GetUpdateResult.NET_REGS_FIRST_EXCEPTION.getCode()+"");
                  info.setResultMessage(GetUpdateResult.NET_REGS_FIRST_EXCEPTION.getMessage());
                  return;
                }
                //TODO 缺少参数
                String ub= submit.elementTextTrim("ub");
                String uid= submit.elementTextTrim("uid");
                userTransLogin(cid, chid, cpid, imei, imsi, sdkSessionId, model, ub, uid, sdkVersion, info);
            }
        } catch (Exception e){
            logger.error(GetUpdateResult.NET_REGS_FIRST_EXCEPTION.getMessage(),e);
            info.setResultCode(GetUpdateResult.NET_REGS_FIRST_EXCEPTION.getCode() + "");
            info.setResultMessage(GetUpdateResult.NET_REGS_FIRST_EXCEPTION.getMessage()+e.getMessage());
        }
    }
    
    //向我方服务器获取反向验证信息接口
    public static void userTransLogin(String cid, String chid, String cpid,String imei, String imsi, String sdkSessionId, String model,String ub,String uid, String sdkVersion, DoRegsInfo info) {
        //+Signature-OF-Secret+POST+channelId=41457000&contentId=608816024859&cpId=772088&cpparam=&ua=TCL S838M&ub=bb791c2250112a416be86376ceea2eef&uid=1406463077
        String signerContent = "+Signature-OF-Secret+POST+channelId="+chid+"&contentId="+cid+"&cpId="+cpid+"&cpparam=&ua="+model+"&ub="+ub+"&uid="+uid;
        String signer = RegsUtils.encryptSHA1(signerContent);
        try {
            HttpPost httpPost = new HttpPost("http://drm.cmgame.com/egsb/securityCounting/userTransLogin");
            ArrayList<NameValuePair> form = new ArrayList();
            form.add(new BasicNameValuePair("uid", uid));
            form.add(new BasicNameValuePair("ub", ub));
            form.add(new BasicNameValuePair("contentId", cid));
            form.add(new BasicNameValuePair("cpId", cpid));
            form.add(new BasicNameValuePair("channelId", chid));
            form.add(new BasicNameValuePair("cpparam", ""));
            form.add(new BasicNameValuePair("ua", model));
            form.add(new BasicNameValuePair("needNotifyCP", "1"));
            httpPost.addHeader("Accept", "application/xml");
            httpPost.addHeader("Accept-Encoding", "gzip");
            httpPost.addHeader("apiVersion", "2.0");
            httpPost.addHeader("imei", imei);
            httpPost.addHeader("imsi", imsi);
            httpPost.addHeader("OS_TYPE", "1");
            httpPost.addHeader("platform", "Android");
            httpPost.addHeader("Response-Type", "xml");
            httpPost.addHeader("sdkSessionId", sdkSessionId);
            httpPost.addHeader("SDKVersion", sdkVersion);
            httpPost.addHeader("signer", signer);
            httpPost.addHeader("X-OF-KEY", "Signature-OF-RSAUtils");
            httpPost.addHeader("X-OF-Signature", signer);
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(form, "UTF-8");
            urlEncodedFormEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            httpPost.setEntity(urlEncodedFormEntity);
            HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                String result = EntityUtils.toString(httpResponse.getEntity());
            }
        } catch (Exception e) {
            info.setResultCode(GetUpdateResult.NET_REGS_REVERSE_EXCEPTION.getCode() + "");
            info.setResultMessage(GetUpdateResult.NET_REGS_REVERSE_EXCEPTION.getMessage());
        } 
    }
    
    public static String sdkClientVoucher(String cid, String chid, String imei, String imsi, String sdkSessionId, String cpId) throws DocumentException {
		// +Signature-OF-Secret+POST+channelId=41457000&contentId=608816024859
		String signerContent = "+Signature-OF-Secret+POST+channelId=" + chid + "&contentId=" + cid;
		String signer = RegsUtils.encryptSHA1(signerContent);
		ArrayList<NameValuePair> form = new ArrayList<NameValuePair>();
		form.add(new BasicNameValuePair("contentId", cid));
		form.add(new BasicNameValuePair("channelId", chid));
		try {
			HttpPost httpPost = new HttpPost("http://drm.cmgame.com/egsb/accountManage/SDKClientVoucher");
			httpPost.addHeader("Accept", "application/xml");
			httpPost.addHeader("Accept-Encoding", "gzip");

			httpPost.addHeader("apiVersion", "2.0");

			httpPost.addHeader("imei", imei);
			httpPost.addHeader("imsi", imsi);

			httpPost.addHeader("OS_TYPE", "1");
			httpPost.addHeader("platform", "Android");
			httpPost.addHeader("Response-Type", "xml");
			httpPost.addHeader("sdkSessionId", sdkSessionId);
			httpPost.addHeader("SDKVersion", RegsUtils.SDK_VERSION_120);
			httpPost.addHeader("signer", signer);
			httpPost.addHeader("X-OF-KEY", "Signature-OF-RSAUtils");
			httpPost.addHeader("X-OF-Signature", signer);
			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(form, "UTF-8");
			urlEncodedFormEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			httpPost.setEntity(urlEncodedFormEntity);
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity());
				Document doc = DocumentHelper.parseText(result);
                Element rootElement = doc.getRootElement();// 获取根节点
                return rootElement.elementTextTrim("clientVoucher");
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
    
    public static String checkLoginPolicy(String cid, String chid, String cpId, String imei, String imsi, String sdkSessionId) {
		String ms = "";
		// +Signature-OF-Secret+POST+chid=41457000&cid=608816024859&cpId=772088&ms=
		String signerContent = "+Signature-OF-Secret+POST+chid=" + chid + "&cid=" + cid + "&cpId=" + cpId + "&ms=" + ms;
		String signer = RegsUtils.encryptSHA1(signerContent);
		ArrayList<NameValuePair> form = new ArrayList();
		form.add(new BasicNameValuePair("cid", cid));
		form.add(new BasicNameValuePair("cpId", cpId));
		form.add(new BasicNameValuePair("chid", chid));
		form.add(new BasicNameValuePair("ms", ms));
		try {
			HttpPost httpPost = new HttpPost("http://wap.cmgame.com:7758/normandie/CheckLoginPolicy");

			httpPost.addHeader("Accept", "application/xml");
			httpPost.addHeader("Accept-Encoding", "gzip");

			httpPost.addHeader("apiVersion", "2.0");

			httpPost.addHeader("imei", imei);
			httpPost.addHeader("imsi", imsi);

			httpPost.addHeader("OS_TYPE", "1");
			httpPost.addHeader("platform", "Android");
			httpPost.addHeader("Response-Type", "xml");
			httpPost.addHeader("sdkSessionId", sdkSessionId);
			httpPost.addHeader("SDKVersion", RegsUtils.SDK_VERSION_120);
			httpPost.addHeader("signer", signer);
			httpPost.addHeader("X-OF-KEY", "Signature-OF-RSAUtils");
			httpPost.addHeader("X-OF-Signature", signer);
			UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(form, "UTF-8");
			urlEncodedFormEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			httpPost.setEntity(urlEncodedFormEntity);
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				return EntityUtils.toString(httpResponse.getEntity());
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
    
    public static String queryConfigPolicy(String cid, String chid, String cpId, String imei, String imsi, String sdkSessionId) throws DocumentException {
		String signerContent = "+Signature-OF-Secret+POST+";
		String signer = RegsUtils.encryptSHA1(signerContent);
		StringBuilder xml = new StringBuilder();
		xml.append("<?xml version=\"1.0\" encoding=\"utf-8\"?><REQ><cId>");
		xml.append(cid);
		xml.append("</cId><chId>");
		xml.append(chid);
		xml.append("</chId><uniqId>");
		xml.append("");
		xml.append("</uniqId><gameType>");
		xml.append("6");
		xml.append("</gameType></REQ>");
		ArrayList<NameValuePair> form = new ArrayList();
		form.add(new BasicNameValuePair("", xml.toString()));
		StringEntity output = null;
		try {
			output = new StringEntity(xml.toString());
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try {
			HttpPost httpPost = new HttpPost("http://wap.cmgame.com:7758/normandie/QueryConfigPolicy");
			httpPost.addHeader("Accept", "application/xml");
			httpPost.addHeader("Accept-Encoding", "gzip");

			httpPost.addHeader("apiVersion", "2.0");

			httpPost.addHeader("imei", imei);
			httpPost.addHeader("imsi", imsi);

			httpPost.addHeader("OS_TYPE", "1");
			httpPost.addHeader("platform", "Android");
			httpPost.addHeader("Response-Type", "xml");
			httpPost.addHeader("sdkSessionId", sdkSessionId);
			httpPost.addHeader("SDKVersion", RegsUtils.SDK_VERSION_120);
			httpPost.addHeader("signer", signer);
			httpPost.addHeader("X-OF-KEY", "Signature-OF-RSAUtils");
			httpPost.addHeader("X-OF-Signature", signer);
			httpPost.setEntity(output);
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);

			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity());
				Document doc = DocumentHelper.parseText(result);
                Element rootElement = doc.getRootElement();// 获取根节点
                result = rootElement.elementTextTrim("hRet");
				return result;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return null;
	}
    
    public static String eventLoggingAccept1(String cid, String chid, String brand, String model, String imei, String sdkSessionId, String cpId, String uuid, String macAddr, String screen,
			String packageName, String appName, String versionName, String versionCode) throws DocumentException {
		SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String data = "sdkSessionId@" + sdkSessionId + ",tel@,uid@,sdkType@1,sdkVer@" + RegsUtils.SDK_VERSION_120 + ",logVer@2.0,serviceType@6,cpId@" + cpId + ",contentId@" + cid + ",channelId@" + chid
				+ ",installFlag@,startFlag@,packer@,uuid@" + uuid + ",imei@" + imei + ",imsi@0,macAddr@" + macAddr + ",brand@" + brand + ",model@" + model + ",operator@0,network@0,invokeTime@"
				+ localSimpleDateFormat.format(new Date()) + ",eventInvokeTime@" + eventInvokeTime() + ",smsResult@0,eventId@E0007,smsDescn@0,eventType@7,screen@" + screen + ",os@" + getOs()
				+ ",location@,isRooted@" + isRooted() + ",smsFirewall@0,packageName@" + packageName + ",displayName@" + appName + ",versionName@" + versionName + ",versionCode@" + versionCode;
		String signerContent = "+Signature-OF-Secret+POST+data=" + data;
		String signer = RegsUtils.encryptSHA1(signerContent);
		try {
			HttpPost httpPost = new HttpPost("http://sdklog.cmgame.com/behaviorLogging/eventLogging/accept?");
			httpPost.addHeader("Accept", "application/xml");
			httpPost.addHeader("Accept-Encoding", "gzip");

			httpPost.addHeader("apiVersion", "2.0");

			httpPost.addHeader("imei", imei);
			httpPost.addHeader("imsi", "0");

			httpPost.addHeader("OS_TYPE", "1");
			httpPost.addHeader("platform", "Android");
			httpPost.addHeader("Response-Type", "xml");
			httpPost.addHeader("sdkSessionId", sdkSessionId);
			httpPost.addHeader("SDKVersion", RegsUtils.SDK_VERSION_120);
			httpPost.addHeader("signer", signer);
			httpPost.addHeader("X-OF-KEY", "Signature-OF-RSAUtils");
			httpPost.addHeader("X-OF-Signature", signer);
			StringEntity entity = new StringEntity("data=" + URLEncoder.encode(data));
			entity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			httpPost.setEntity(entity);
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity());
				Document doc = DocumentHelper.parseText(result);
                Element rootElement = doc.getRootElement();// 获取根节点
                result = rootElement.elementTextTrim("status");
				return result;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
    
    public static String eventLoggingAccept2(String cid, String chid, String brand, String model, String imei, String sdkSessionId, String cpId, String uuid, String macAddr, String screen,
			String packageName, String appName, String versionName, String versionCode) throws DocumentException {
		SimpleDateFormat localSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String data = "sdkSessionId@" + sdkSessionId + ",tel@,uid@,sdkType@1,sdkVer@20120,logVer@2.0,serviceType@6,cpId@" + cpId + ",contentId@" + cid + ",channelId@" + chid
				+ ",installFlag@,startFlag@,packer@,uuid@" + uuid + ",imei@" + imei + ",imsi@0,macAddr@" + macAddr + ",brand@" + brand
				+ ",model@"+model+",operator@0,network@0,invokeTime@"+localSimpleDateFormat.format(new Date())+",eventInvokeTime@"+eventInvokeTime()+",eventId@E0001,eventType@1";
		String signerContent = "+Signature-OF-Secret+POST+data=" + data;
		String signer = RegsUtils.encryptSHA1(signerContent);
		try {
			HttpPost httpPost = new HttpPost("http://sdklog.cmgame.com/behaviorLogging/eventLogging/accept?");
			httpPost.addHeader("Accept", "application/xml");
			httpPost.addHeader("Accept-Encoding", "gzip");

			httpPost.addHeader("apiVersion", "2.0");

			httpPost.addHeader("imei", imei);
			httpPost.addHeader("imsi", "0");

			httpPost.addHeader("OS_TYPE", "1");
			httpPost.addHeader("platform", "Android");
			httpPost.addHeader("Response-Type", "xml");
			httpPost.addHeader("sdkSessionId", sdkSessionId);
			httpPost.addHeader("SDKVersion", RegsUtils.SDK_VERSION_120);
			httpPost.addHeader("signer", signer);
			httpPost.addHeader("X-OF-KEY", "Signature-OF-RSAUtils");
			httpPost.addHeader("X-OF-Signature", signer);
			StringEntity entity = new StringEntity("data=" + URLEncoder.encode(data));
			entity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
			httpPost.setEntity(entity);
			HttpResponse httpResponse = new DefaultHttpClient().execute(httpPost);
			if (httpResponse.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(httpResponse.getEntity());
				Document doc = DocumentHelper.parseText(result);
                Element rootElement = doc.getRootElement();// 获取根节点
                result = rootElement.elementTextTrim("status");
				return result;
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
    
    public static String getOs() {
		switch (r.nextInt(5)) {
		case 0:
			return "2.3";
		case 1:
			return "4.0";
		case 2:
			return "4.1";
		case 3:
			return "4.2";
		case 4:
			return "4.3";
		default:
			return "4.4";
		}
	}
    
    public static int isRooted() {
		return r.nextInt(2);
	}
    
    public static int eventInvokeTime() {
		return  r.nextInt(20);
	}

	public static String getUuid() {
		return UUID.randomUUID().toString().replace("-", "");
	}
	
	public static String getMacAddr(){
		String result = "";
		for(int i=0; i<12; i++){
			result+=Integer.toHexString(r.nextInt(12)).toUpperCase();
		}
		return result;
	}
}
